package com.roomio.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.MessageDigest;
import org.apache.commons.codec.binary.Base64;

/**
 * Utility Class to encode passwords programmatically
 * 
 * @author <a href="mailto:og.tech79@gmail.com">Shailendra Sinha</a>
 */
public class PasswordUtil {

	private static final Logger log = LoggerFactory.getLogger(PasswordUtil.class);
	
	/**
     * Encode a string using algorithm specified in web.xml and return the
     * resulting encrypted password. If exception, the plain credentials
     * string is returned
     *
     * @param password Password or other credentials to use in authenticating
     *        this username
     * @param algorithm Algorithm used to do the digest
     *
     * @return encypted password based on the algorithm.
     */
    public static String encodePassword(String password, String algorithm) {
        byte[] unencodedPassword = password.getBytes();

        MessageDigest md = null;

        try {
            // first create an instance, given the provider
            md = MessageDigest.getInstance(algorithm);
        } catch (Exception e) {
            log.error("Exception: " + e);

            return password;
        }

        md.reset();

        // call the update method one or more times
        // (useful when you don't know the size of your data, eg. stream)
        md.update(unencodedPassword);

        // now calculate the hash
        byte[] encodedPassword = md.digest();

        StringBuffer buf = new StringBuffer();

        for (int i = 0; i < encodedPassword.length; i++) {
            if ((encodedPassword[i] & 0xff) < 0x10) {
                buf.append("0");
            }

            buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
        }

        return buf.toString();
    }

    /**
     * Encode a string using Base64 encoding. Used when storing passwords
     * as cookies.
     *
     * This is weak encoding in that anyone can use the decodeString
     * routine to reverse the encoding.
     *
     * @param str
     * @return String
     */
    public static String encodeString(String str)  {
    	return new String (Base64.encodeBase64(str.getBytes()));
    }
    public static String encodeString(byte[] bytes)  {
    	return new String (Base64.encodeBase64(bytes));
    }
    /**
     * Decode a string using Base64 encoding.
     *
     * @param str
     * @return String
     */
    public static byte[] decodeString(String str) {
    	try{
    		return Base64.decodeBase64(str.getBytes());
    	}catch (Exception e) {
    		throw new RuntimeException(e.getMessage(), e.getCause());
		}
    	
    }
    
    public static String getRandomPassword(){
    	int n=8;
        char[] pw = new char[n];
        int c  = 'A';
        int  r1 = 0;
        for (int i=0; i < n; i++)
        {
          r1 = (int)(Math.random() * 3);
          switch(r1) {
            case 0: c = '0' +  (int)(Math.random() * 10); break;
            case 1: c = 'a' +  (int)(Math.random() * 26); break;
            case 2: c = 'A' +  (int)(Math.random() * 26); break;
          }
          pw[i] = (char)c;
        }
        return new String(pw);
    }
}
